package org.edu.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.RequestAware;
import org.edu.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
/**
 * <h2>上传文件Action</h2>
 * <p>已在方法上注明方法作用</p>
 * <p>该类详细配置了上传文件方法</p>
 * @author 谢圣强
 * @version 2.0
 */
@Controller
@ParentPackage("struts-default")
// 表示继承的父包
//父包  
@Namespace("/openfile")
@InterceptorRefs(value = { @InterceptorRef("fileUploadStack") }) 
@Result(name = "success", location = "/examples/section.jsp")
// 表示当前Action所在命名空间
public class UpFileAction extends ActionSupport implements RequestAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6925051432577672306L;
	
	private static final Logger logger = Logger.getLogger(UpFileAction.class);
	
	//文件长度
	public static final long maximumsize=10485760  ;//10M
	public static final String FILE_NAME="sector_Information.xls";
	/*
	 * application/vnd.ms-excel=xls
	 * application/msword=doc
	 * application/octet-stream=无限制
	 * application/vnd.openxmlformats-officedocument.spreadsheetml.sheet=xlsx
	 * application/octet-stream=java
	 * text/plain=text
	 * image/jpeg=jpg
	 * 
	 * 
	 * */
	//文件类型
	public static final String[] FILE_TYPE={"application/vnd.ms-excel","application/octet-stream"
										,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
	private static final int BUFFER_SIZE = 16 * 1024;
	private File file;
	private String seclectid;
	
	@Autowired
	private DeptService deptService;
	
    // 封装上传文件类型的属性  
    private String fileContentType;  //上传文件的类型， ContentType 固定的写法  
    // 封装上传文件名的属性  
    private String fileFileName;// 上传文件的名字 ,FileName 固定的写法  
    
   // private ContentAttach contentAttachs;//附件对象 
    
    
    //重定向到examples/index  不过定向到另外一个action 比较好 可以带参数
    @Action(value="upload",results = {@Result(name = "success", location = "/examples/index.jsp?collapse=collapseFour",type="redirect"),
    @Result(name = "error", location = "/examples/section.jsp")})  //搞个错误页面
	public String upFile() throws IOException{
//		System.out.println("文件名"+fileFileName);
//		System.out.println("文件类型"+fileContentType);
//		System.out.println("文件大小"+file.length());
//		System.out.println("文件临时路径"+file.getAbsolutePath());
		ServletContext rel=ServletActionContext.getServletContext();
		File uploadFile = new File(rel.getRealPath("xls"));
		if (!uploadFile.exists()) {//判断输出路径是否存在
            uploadFile.mkdir();  
        }
		boolean istype=false;
		for (int i = 0; i < FILE_TYPE.length; i++) {
			if(FILE_TYPE[i].equalsIgnoreCase(fileContentType)){
				istype=true;
				break;
			}
		}
		if(!istype) {
			request.put("tip", "文件类型不符");
			logger.info("上传文件失败,文件类型不符");
			return SUCCESS;
		}
		if(maximumsize<file.length()){
			request.put("tip", "请勿上传超过10M 的文件");
			logger.info("上传文件失败,文件太大");
			return SUCCESS;
		}
		File xls = new File(uploadFile,FILE_NAME);
		copy(file,xls);
		request.put("tip", "上传成功");
		//logger.info("上传成功，正在更新数据");
		try {
		deptService.savexlsWdataUpload(xls);
		
		} catch(NumberFormatException e){
			request.put("tip", "读取文件失败，格式不符合 标准，注 ：这里应是错误页面，懒得写");
        	logger.info("读取文件失败，上传失败！");
        	return ERROR;
		}catch (IOException e) {  
        	request.put("tip", "写入数据库出现意外，请联系管理员。上传失败！");
        	logger.info("写入数据库出现意外，上传失败！");
        	xls.delete();//删除上传的文件
        } 
		//request.put("collapse", "collapseFour");
		return SUCCESS;
	}
    
    /**
     * 复制文件
     * @param src 需要复制的文件
     * @param dst 目标
     */
    public void copy(File src, File dst) {  
        try {  
            InputStream in = null;  
            OutputStream out = null;  
            try {  
                in = new BufferedInputStream(new FileInputStream(src),  
                        BUFFER_SIZE);  
                out = new BufferedOutputStream(new FileOutputStream(dst),  
                        BUFFER_SIZE);  
                byte[] buffer = new byte[BUFFER_SIZE];  
                while (in.read(buffer) > 0) {  
                    out.write(buffer);  
                }  
            } 
            finally { 
            	
            	
                if (null != in) {  
                    in.close();  
                }  
                if (null != out) {  
                    out.close();  
                }  
            }  
        } catch (Exception e) {  
        	request.put("tip", "传输过程中出现意外错误，请联系管理员。上传失败！");
        	logger.info("传输过程中出现意外错误，上传失败！");
        }  
    }  
	private Map<String, Object> request;

	public Map<String, Object> getRequest() {
		return request;
	}

	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getSeclectid() {
		return seclectid;
	}
	public void setSeclectid(String seclectid) {
		this.seclectid = seclectid;
	}
}
